﻿#define CODE_ANALYSIS

using System.Linq;
using System;
using System.Diagnostics.CodeAnalysis;
#if SILVERLIGHT
using System.Windows;
using System.Windows.Controls;
#else
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
#endif

namespace Microsoft.PlayerFramework
{
    /// <summary>
    /// A plugin used to show the user that an error occured.
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Correctly named architectural pattern")]
#if MEF
    [System.ComponentModel.Composition.PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
    [System.ComponentModel.Composition.Export(typeof(IPlugin))]
#endif
    public sealed class ErrorPlugin : PluginBase
    {
        ErrorView errorViewElement;
        Panel errorContainer;

        /// <summary>
        /// Gets or sets the style to be used for the ErrorView
        /// </summary>
        public Style ErrorViewStyle { get; set; }

        /// <inheritdoc /> 
        protected override bool OnActivate()
        {
            errorContainer = MediaPlayer.Containers.OfType<Panel>().FirstOrDefault(e => e.Name == MediaPlayerTemplateParts.ErrorsContainer);
            if (errorContainer != null)
            {
                errorViewElement = new ErrorView()
                {
                    Style = ErrorViewStyle
                };
                errorViewElement.RetryCommand = new DelegateCommand(MediaPlayer.Retry);
                errorContainer.Children.Add(errorViewElement);
                return true;
            }
            return false;
        }

        /// <inheritdoc /> 
        protected override void OnDeactivate()
        {
            errorContainer.Children.Remove(errorViewElement);
            errorViewElement = null;
            errorContainer = null;
        }
    }
}
